<template>
  <div class="data-list-view">
    <div class="page-header">
      <h1>数据列表</h1>
      <el-button type="primary" @click="navigateToForm">
        <el-icon><Plus /></el-icon> 新增数据
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="filterForm.keyword" 
            placeholder="请输入名称或描述" 
            clearable 
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="活跃" value="active" />
            <el-option label="非活跃" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="filterForm.category" placeholder="请选择分类" clearable>
            <el-option label="类型A" value="类型A" />
            <el-option label="类型B" value="类型B" />
            <el-option label="类型C" value="类型C" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <div class="card-header">
          <span>数据列表</span>
          <div class="header-actions">
            <el-button type="primary" plain size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
            <el-button type="danger" plain size="small" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon> 批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '活跃' : '非活跃' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="dataStore.totalCount"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDataStore, DataItem } from '../store'
import { 
  Plus, 
  Search, 
  Refresh, 
  Delete 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from '../utils/common'

const router = useRouter()
const dataStore = useDataStore()

// 加载状态
const loading = ref(false)

// 筛选表单
const filterForm = ref({
  keyword: '',
  status: '',
  category: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 选中的行
const selectedRows = ref<DataItem[]>([])

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    await dataStore.fetchDataList()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 过滤后的数据
const filteredData = computed(() => {
  let result = dataStore.dataList

  // 关键词过滤
  if (filterForm.value.keyword) {
    const keyword = filterForm.value.keyword.toLowerCase()
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.description.toLowerCase().includes(keyword)
    )
  }

  // 状态过滤
  if (filterForm.value.status) {
    result = result.filter(item => item.status === filterForm.value.status)
  }

  // 分类过滤
  if (filterForm.value.category) {
    result = result.filter(item => item.category === filterForm.value.category)
  }

  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value

  return result.slice(startIndex, endIndex)
})

// 搜索输入防抖处理
const handleSearchInput = debounce(() => {
  currentPage.value = 1
}, 300)

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    keyword: '',
    status: '',
    category: ''
  }
  currentPage.value = 1
}

// 刷新数据
const handleRefresh = () => {
  loadData()
}

// 处理编辑
const handleEdit = (row: DataItem) => {
  dataStore.setCurrentItem(row)
  router.push(`/data-form?id=${row.id}`)
}

// 处理删除
const handleDelete = (row: DataItem) => {
  ElMessageBox.confirm(
    `确定要删除 "${row.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    dataStore.deleteDataItem(row.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    selectedRows.value.forEach(row => {
      dataStore.deleteDataItem(row.id)
    })
    ElMessage.success(`成功删除 ${selectedRows.value.length} 条数据`)
    selectedRows.value = []
  }).catch(() => {
    // 取消删除
  })
}

// 选择行变化
const handleSelectionChange = (rows: DataItem[]) => {
  selectedRows.value = rows
}

// 页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 跳转到表单页
const navigateToForm = () => {
  dataStore.setCurrentItem(null)
  router.push('/data-form')
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.data-list-view {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-light);
}

.page-header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: var(--shadow-sm) !important;
  transition: box-shadow var(--transition-normal);
}

.filter-card:hover {
  box-shadow: var(--shadow-md) !important;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.data-table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: var(--shadow-sm) !important;
  transition: box-shadow var(--transition-normal);
}

.data-table-card:hover {
  box-shadow: var(--shadow-md) !important;
}

.data-table-card :deep(.el-card__header) {
  padding: 16px 20px;
  background-color: rgba(var(--primary-color), 0.03);
  border-bottom: 1px solid var(--border-light);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: rgba(var(--primary-color), 0.05);
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-table td) {
  color: var(--text-regular);
}

:deep(.el-button) {
  transition: all var(--transition-normal);
}

:deep(.el-pagination) {
  --el-pagination-button-bg-color: var(--primary-color);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .header-actions {
    margin-top: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style> 